package com.learning.security.core;

import com.learning.security.dal.dataobject.AdminApiDO;
import com.learning.security.dal.dataobject.AdminRightDO;
import com.learning.security.dal.dataobject.AdminRoleDO;
import com.learning.security.dal.dataobject.AdminRoleRightDO;
import com.learning.security.service.AdminApiService;
import com.learning.security.service.AdminRightService;
import com.learning.security.service.AdminRoleRightService;
import com.learning.security.service.AdminRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

@Component
public class DefaultSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    @Autowired
    private AdminApiService adminApiService;

    @Autowired
    private AdminRightService adminRightService;

    @Autowired
    private AdminRoleRightService adminRoleRightService;

    @Autowired
    private AdminRoleService adminRoleService;


    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String requestURI = ((FilterInvocation) object).getRequest().getRequestURI();
        AdminApiDO apiDO = adminApiService.getApiByPath(requestURI);
        if (Objects.isNull(apiDO)) {
            return Collections.emptyList();
        }
        AdminRightDO rightDO = adminRightService.getRightByPermission(apiDO.getPermission());
        if (Objects.isNull(rightDO)) {
            return Collections.emptyList();
        }
        List<AdminRoleRightDO> roleRightDOList = adminRoleRightService.getRoleRightByRightId(rightDO.getId());

        String[] roles = roleRightDOList.stream().map(roleRight -> adminRoleService.getRoleByRoleId(roleRight.getRoleId()))
                .map(AdminRoleDO::getCode).toArray(String[]::new);
        if (roles.length > 0) {
            return SecurityConfig.createList(roles);
        }
        return Collections.emptyList();
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return Collections.emptyList();
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return false;
    }
}
